<template>
  <div class="category">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
      <el-breadcrumb-item>产品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 条件搜索 -->
      <el-row>
        <el-col :span="10">
          <el-input
            placeholder="请输入需要查询的内容"
            v-model="namesearch"
            clearable
            @clear="clearsearch()"
          >
            <template slot="prepend">按分类名称查询：</template>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="Search()"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-button
        type="primary"
        size="mini"
        class="insbut"
        icon="el-icon-circle-plus-outline"
        @click="dialogFormVisible = true"
        >新增分类</el-button
      >
      <!-- 新增 编辑图书类型对话框 -->
      <el-dialog
        :title="isEdit ? '编辑' : '新增类型'"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="类型名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="类型备注"
            :label-width="formLabelWidth"
            prop="note"
          >
            <el-input v-model="form.note" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="isEdit" type="primary" @click="Updatebookscategory"
            >提 交</el-button
          >
          <el-button v-else type="primary" @click="Insertbookscategory('form')"
            >新 增</el-button
          >
        </div>
      </el-dialog>
      <!-- 加载图书类型数据 -->
      <el-table :data="tableData1" border stripe>
        <el-table-column
          type="index"
          :index="indexNum"
          label="序号"
          width="60"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="name" label="分类名称" width="80" align="center">
        </el-table-column>
        <el-table-column prop="note" label="分类备注" width="" align="center">
        </el-table-column>
        <el-table-column
          prop="createtime"
          label="创建时间"
          width=""
          align="center"
        >
        </el-table-column>
        <el-table-column label="启用/禁用" width="140" align="center">
          <template slot-scope="scpoe">
            <el-switch
              v-model="scpoe.row.state"
              active-text="启用"
              inactive-text="禁用"
              @change="toggle(scpoe.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="Editbookscategory(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="Deletebookscategory(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @next-click="handleNextClick"
        @prev-click="handlePrevClick"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        :current-page="currentpage"
        background
        layout="total,sizes, prev, pager, next, jumper"
        :total="tableData_length"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  data() {
    return {
      form: {
        name: "",
        note: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入图书类型", trigger: "blur" },
          { min: 2, message: "长度至少两个字符", trigger: "blur" }
        ],
        note: [
          { required: true, message: "请输入分类备注", trigger: "blur" },
          { min: 1, message: "长度至少一个字符", trigger: "blur" }
        ]
      },
      tableData: [],
      tableData1: [], //分页显示的数据
      formLabelWidth: "80px",
      dialogFormVisible: false,
      namesearch: "",
      isEdit: false,
      currentpage: 1, //当前页面
      tableData_length: 0, //总条目数
      pageSize: 5
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    //获取图书分类列表
    init() {
      const that = this;
      that.$http
        .get("/selectbookscategory")
        .then(res => {
          // console.log(res);
          that.tableData = res.data.data;
          that.tableData_length = res.data.data.length;
          this.handleCurrentChange(1); //默认显示第一页条目
          for (let i in that.tableData) {
            if (that.tableData[i].state == 1) {
              that.tableData[i].state = true;
            } else {
              that.tableData[i].state = false;
            }
          }
        })
        .catch(function() {});
    },
    //新增图书分类
    Insertbookscategory(form) {
      const that = this;
      that.$refs[form].validate(valid => {
        if (valid) {
          that.$http
            .post("/insertbookscategory", that.form)
            .then(res => {
              if (res.status == 204) {
                that.$message({
                  message: "新增图书分类成功...",
                  type: "success"
                });
                that.init();
              } else {
                that.$message({
                  message: "新增图书分类失败...",
                  type: "error"
                });
              }
              // console.log(res);
              that.dialogFormVisible = false;
              that.form.name = null;
              that.form.note = null;
            })
            .catch(function() {});
        } else {
          that.$message({
            message: "请完善图书信息...",
            type: "error"
          });
        }
      });
    },
    //编辑获取数据至表单
    Editbookscategory(item) {
      this.isEdit = true;
      this.dialogFormVisible = true;
      this.form = JSON.parse(JSON.stringify(item));
    },
    //修改图书分类
    Updatebookscategory() {
      const that = this;
      that.$http
        .post("/updatebookscategory", that.form)
        .then(res => {
          if (res.status == 204) {
            that.$message({
              message: "更新数据成功...",
              type: "success"
            });
            that.reload();
            that.dialogFormVisible = false;
            that.isEdit = false;
          } else {
            that.$message({
              message: "更新数据失败...",
              type: "error"
            });
          }
          // console.log(res);
          that.dialogFormVisible = false;
          that.form.note = null;
          that.form.name = null;
        })
        .catch(function() {});
    },
    //删除图书分类
    Deletebookscategory(id) {
      const that = this;
      that
        .$confirm("此操作将数据永久删除,不可恢复, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
        .then(() => {
          that.$http.post("/deletebookscategory", { id }),
            that.$message({
              type: "success",
              message: "删除成功!"
            });
          for (let i in that.tableData1) {
            if (that.tableData1[i].id == id) {
              that.tableData1.splice(i, 1); //删除不请求数据，直接在数组中删除
              break;
            }
          }
        })
        .catch(() => {
          that.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // switch开关改变 触发的回调函数 禁用或开启
    toggle(id) {
      this.$http.post("/bookscategoryswitch", { id });
    },
    //element table自带序号
    indexNum(index) {
       return (this.currentpage - 1) * this.pageSize + index + 1;
    },
    //处理数据,分页
    handleTableData() {
      this.tableData1 = this.tableData.slice(
        (this.currentpage - 1) * this.pageSize,
        this.currentpage * this.pageSize
      );
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleTableData();
    },
    //点击中间页的按钮 执行的方法
    handleCurrentChange(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //点击向前的按钮 执行的方法
    handlePrevClick(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //点击向后的按钮 执行的方法
    handleNextClick(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //清除搜索框
    clearsearch() {
      this.init();
    },
    //搜索
    Search() {
      if (this.namesearch == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      } else {
        let search = this.namesearch;
        this.tableData = this.tableData.filter(item => {
          let searchField = { name: item.name };
          return Object.keys(searchField).some(key => {
            return (
              String(item[key])
                .toLowerCase()
                .indexOf(search) > -1
            );
          });
        });
      }
      this.tableData_length = this.tableData.length;
      this.handleCurrentChange(1);
    }
  }
};
</script>

<style scoped>
.el-input {
  margin-bottom: 8px;
}
</style>